<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>购物车功能实现</title>
  <style>
    table {
      border-collapse: collapse;
    }

    thead {
      background-color: #f5f5f5;
    }

    th, td {
      border: 1px solid #000;
      padding: 10px;
    }
  </style>
</head>
<body>
  
  <table>
    <thead>
      <tr>
        <th>编号</th>
        <th>书籍名称</th>
        <th>出版日期</th>
        <th>价格</th>
        <th>购买数量</th>
        <th>操作</th>
      </tr>
    </thead>
  </table>
  <h2 class="price">
    总价：¥<span id="price-count">0</span>
  </h2>

  <script>
    // 1.数据
    const booksData = [
      {
        id: 1,
        name: '《算法导论》',
        date: '2006-9',
        price: 85.00,
        count: 1
      },
      {
        id: 2,
        name: '《UNIX编程艺术》',
        date: '2006-2',
        price: 59.00,
        count: 2
      },
      {
        id: 3,
        name: '《C程序设计语言》',
        date: '2008-10',
        price: 39.00,
        count: 1
      },
      {
        id: 4,
        name: '《代码大全》',
        date: '2006-3',
        price: 128.00,
        count: 4
      },
      {
        id: 5,
        name: '《深入理解计算机系统》',
        date: '2011-3',
        price: 129.00,
        count: 5
      }
    ]

    // 2.获取table
    const tableEl = document.querySelector('table')
    const tbodyEl = document.createElement('tbody')
    const priceCountEl = document.querySelector('#price-count')
    
    let totalPrice = 0
    booksData.forEach((item) => {
      const trContentEl = `
        <tr>
          <td>${item.id}</td>
          <td>${item.name}</td>
          <td>${item.date}</td>
          <td>${item.price}</td>
          <td>${item.count}</td>
          <td>
            <button class="btn btn-danger" data-delete-id="${item.id}">删除</button>
          </td>
        </tr>
      `
      tbodyEl.innerHTML += trContentEl
    })
    tableEl.append(tbodyEl)

    tbodyEl.onclick = function (e) {
      const target = e.target
      if (target.classList.contains('btn-danger')) {
        const deleteId = target.dataset.deleteId
        const deleteIndex = booksData.findIndex((item) => item.id == deleteId)
        booksData.splice(deleteIndex, 1)
        target.parentElement.parentElement.remove()
        countPriceHandler()
      }
    }

    function countPriceHandler() {
      priceCountEl.textContent = booksData.reduce((previousValue, currentValue) => {
        return previousValue + currentValue.price * currentValue.count
      }, 0)
    }
    countPriceHandler()

  </script>

  
</body>
</html>